﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using SSN.Objects;
using SSN.BusinessFramework;
using SSN.BusinessFramework.Accounts;
using SSN.Utilities.Cache;
using SSN.Utilities.Security;
using SSN.DotNet;

namespace SSN.WebFramework
{
    public class AccountManager
    {
        private SSNSecurityContext _ctx = null;
        private KeyValueCache<string, Prefix> _prefCache = new KeyValueCache<string, Prefix>(_initPrefCache, new TimeSpan(4, 0, 0));

        private static Dictionary<string, Prefix> _initPrefCache()
        {
            Dictionary<string, Prefix> table = new Dictionary<string,Prefix>();
            SystemSecurityContext sCtx = new SystemSecurityContext();
            foreach (Prefix p in Prefix.GetAllPrefixes(sCtx))
            {
                table[p.Code] = p;
            }

            return table;
        }

        public AccountManager(SSNSecurityContext context)
        {
            _ctx = context;
        }

        /// <summary>
        /// Returns an account object given a representation of the account (Tradedesk or SNNumber)
        /// </summary>
        /// <param name="text">Tradedesk or SNNumber</param>
        /// <returns>Account object.</returns>
        public Account GetAccount(string text)
        {
            text = text.Trim().ToUpper();
            AccountSearch aSearch = new AccountSearch(_ctx);
            if (text.ToUpper().StartsWith("SN"))
            {
                aSearch.SNNumber = text;
            }
            else
            {
                aSearch.Tradedesk = text;
            }

            List<Account> accounts = aSearch.DoSearch();

            if (accounts != null && accounts.Count == 1)
            {
                return accounts[0];
            }

            return null;
        }

        /// <summary>
        /// Returns prefix information given the prefix code.
        /// </summary>
        /// <param name="prefix"></param>
        /// <returns></returns>
        public Prefix GetPrefix(string prefix)
        {
            return _prefCache[prefix];
        }
    }
}
